"ui";

var args = engines.myEngine().execArgv;
let repoUrl = args.repoUrl;
importClass(Packages.androidx.recyclerview.widget.RecyclerView);
importClass(Packages.androidx.recyclerview.widget.LinearLayoutManager);
importClass(android.graphics.Color);
importClass(Packages.androidx.swiperefreshlayout.widget.SwipeRefreshLayout);
importClass(android.view.View);
let yashuUtil = require("./yashuUtil");
let config = require("./config");
let service = require("./service");

let themeColor = config.themeColor;
let status_bar_height = yashuUtil.status_bar_height;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
let userInfo = config.storage.get("userInfo");
ui.layout(
  <vertical bg="{{themeColor}}" paddingLeft="16" paddingRight="16" paddingTop="{{status_bar_height}}px">
    <frame marginBottom="16">
      <img
        id="back"
        tint="#ffffff"
        src="@drawable/ic_keyboard_arrow_left_black_48dp"
        layout_gravity="center_vertical"
        w="40dp"
      ></img>
      <TextView
        id="title"
        textColor="#ffffff"
        textSize="32sp"
        layout_width="wrap_content"
        layout_height="wrap_content"
        layout_centerInParent="true"
        layout_gravity="center"
        text=""
      />
      <img id="share" tint="#ffffff" src="@drawable/ic_share_black_48dp" layout_gravity="right|center" w="40dp"></img>
    </frame>

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
      id="swipeRefreshLayout"
      layout_width="match_parent"
      layout_height="wrap_content"
    >
      <androidx.recyclerview.widget.RecyclerView
        id="recyclerView"
        layout_width="match_parent"
        layout_height="match_parent"
      />
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
  </vertical>
);
/* -------------------------------------------------------------------------- */
ui.swipeRefreshLayout.setRefreshing(true);
// 分享链接
ui.share.on("click", () => {
  let intent = new android.content.Intent(android.content.Intent.ACTION_SEND);
  intent.setType("text/plain");
  intent.putExtra(android.content.Intent.EXTRA_TEXT, repoUrl);
  activity.startActivity(android.content.Intent.createChooser(intent, "分享到"));
});

/* -------------------------------------------------------------------------- */

yashuUtil.setStatusBarFullTransparent();
let repoName = repoUrl.split("/")[4];

ui.title.setText(repoName);
ui.back.on("click", () => {
  engines.myEngine().forceStop();
});

/* -------------------------------------------------------------------------- */
service
  .getTree(repoUrl, "master")
  .then((items) => {
    ui.run(function () {
      ui.swipeRefreshLayout.setRefreshing(false);
      ui.swipeRefreshLayout.setEnabled(false);
    });
    // log(items);
    ui.run(function () {
      // log(items);
      var len = items.length;
      for (var i = 0; i < len; i++) {}
      // 设置布局管理器
      ui.run(function () {
        let layoutManager = new LinearLayoutManager(context);
        ui.recyclerView.setLayoutManager(layoutManager);
        let recycleAdapter = createRecyclerViewAdapter(items);
        ui.recyclerView.setAdapter(recycleAdapter);
      });
    });
  })
  .catch((error) => {});
/* ------------------自定义函数-------------------------------------------------------- */

function createRecyclerViewAdapter(items) {
  let itemLayout = (
    <horizontal gravity="center_vertical" margin="0 8 0 8">
      <img id="img" w="40dp"></img>
      <text paddingLeft="8" id="filename" textColor="#ffffff"></text>
    </horizontal>
  );
  return RecyclerView.Adapter({
    onCreateViewHolder: function (parent, viewType) {
      // log("onCreateViewHolder");
      // 视图创建
      let view;
      let holder;
      view = ui.inflate(itemLayout, parent, false);
      holder = JavaAdapter(RecyclerView.ViewHolder, {}, view);
      view.on("click", function (view) {
        let position = holder.getAdapterPosition();
        let item = items[position];
        // TODO: 点击事件
        if (item.type === "tree") {
          engines.execScriptFile("page/dir-detail.js", {
            arguments: { url: item.url, sha: item.sha, path: item.path },
          });
        } else if (item.type === "blob") {
          if (item.size < config.fileSizeLimit) {
            // 小文件自己写浏览文件
            // 如果是图片就打开图片
            if (item.path.endsWith(".jpg") || item.path.endsWith(".png")) {
              engines.execScriptFile("page/image-detail.js", {
                arguments: { url: item.url, sha: item.sha, path: item.path },
              });
            } else {
              engines.execScriptFile("page/txt-detail.js", {
                arguments: { url: item.url, sha: item.sha, path: item.path },
              });
            }
          } else {
            confirm("文件太大, 要下载吗?").then((clear) => {
              if (clear) {
                // 下载文件, 然后用手机的文件管理器打开
                service.downloadFile(item.url).then((filepath) => {
                  activity.startActivity(
                    new android.content.Intent(
                      android.content.Intent.ACTION_VIEW,
                      android.net.Uri.fromFile(new java.io.File(filepath))
                    )
                  );
                });
              }
            });
          }
        } else {
          toastLog("未知类型");
        }
      });

      return holder;
    },
    onBindViewHolder: function (holder, position) {
      // 数据绑定
      let view = holder.itemView;
      let item = items[position];
      view.filename.setText(item.path);
      if (item.type === "tree") {
        view.img.attr("src", "@drawable/ic_folder_black_48dp");
        view.img.attr("tint", "#79b7ff");
      } else {
        view.img.attr("src", "@drawable/ic_insert_drive_file_black_48dp");
        view.img.attr("tint", "#fffdff");
      }
    },
    getItemCount: function () {
      return items.length;
    },
  });
}
